using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Model.UI;
using IMClient.Model.DTO;
using IMClient.Model;
using IMClient.Config;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Microsoft.Win32;
using System.IO;
using System.Net.Http.Headers;
using IMClient.Cache.Repositories;

namespace IMClient.ViewModels;

public partial class GroupCreatorManagerViewModel : ObservableObject
{
    private readonly HttpClient _httpClient;
    private string _originalName = string.Empty;
    private string _originalAvatar = string.Empty;

    public static event Action<string, string>? GroupAvatarUpdated;
    public static event Action<string, string>? GroupNameUpdated;

    private readonly GroupCacheRepository _groupRepository;
    private readonly ChatRecordRepository _chatRecordRepository;

    [ObservableProperty]
    private string name = string.Empty;

    [ObservableProperty]
    private string avatar = string.Empty;

    [ObservableProperty]
    private string groupId = string.Empty;

    [ObservableProperty]
    private ObservableCollection<FriendViewModel> groupMembers;

    public GroupCreatorManagerViewModel(GroupViewModel group)
    {
        _httpClient = new HttpClient();
        Name = group.Name;
        Avatar = group.Avatar;
        _originalAvatar = group.Avatar;
        GroupId = group.Id;
        GroupMembers = new ObservableCollection<FriendViewModel>();
        _originalName = group.Name;

        _chatRecordRepository = new ChatRecordRepository();
        _groupRepository = GroupCacheRepository.Instance;

        // 加载群成员信息
        _ = LoadGroupMembersAsync();
    }

    [RelayCommand]
    private void DismissGroup()
    {
        MessageBox.Show("解散群聊功能待实现");
    }

    [RelayCommand]
    private void SendMessage()
    {
        var chatViewModel = ChatWindowViewModel.Instance.GetChatPageViewModel();

        if (chatViewModel == null)
            return;

        var existingGroup = chatViewModel.ChatParticipants
            .FirstOrDefault(g => g.Id == GroupId);

        if (existingGroup == null)
        {
            var newGroup = new GroupViewModel
            {
                Id = GroupId,
                Name = Name,
                Avatar = Avatar,
                LastMessage = string.Empty,
                LastMessageTime = string.Empty,
                UnreadCount = 0
            };
            chatViewModel.ChatParticipants.Add(newGroup);
            chatViewModel.FilterParticipants(string.Empty);
            chatViewModel.SelectedParticipant = newGroup;
        }
        else
        {
            chatViewModel.SelectedParticipant = existingGroup;
        }

        ChatWindowViewModel.Instance.NavigateToChat();
    }

    [RelayCommand]
    private void SelectAvatar()
    {
        var openFileDialog = new OpenFileDialog
        {
            Filter = "Image Files (*.png;*.jpg;*.jpeg)|*.png;*.jpg;*.jpeg|All Files (*.*)|*.*",
            RestoreDirectory = true,
            Title = "请选择群头像"
        };

        if (openFileDialog.ShowDialog() == true)
        {
            var result = MessageBox.Show(
                "确定要修改群头像吗？", 
                "修改群头像", 
                MessageBoxButton.OKCancel, 
                MessageBoxImage.Question);

            if (result == MessageBoxResult.OK)
            {
                _ = UpdateGroupAvatarAsync(openFileDialog.FileName);
            }
        }
    }

    private async Task LoadGroupMembersAsync()
    {
        try
        {
            var request = new HttpRequestMessage(HttpMethod.Post, $"{NetWorkConfig.BaseUrl}/group/groupinfo");
            var content = new StringContent(
                JsonSerializer.Serialize(new { groupId = GroupId }), 
                Encoding.UTF8, 
                "application/json");
            request.Content = content;

            var response = await _httpClient.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                var jsonResponse = await response.Content.ReadAsStringAsync();
                var groupInfo = JsonSerializer.Deserialize<GroupInfoResponseDto>(jsonResponse);

                if (groupInfo?.Code == "0000" && groupInfo.Data?.Members != null)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        GroupMembers.Clear();
                        foreach (var member in groupInfo.Data.Members)
                        {
                            GroupMembers.Add(new FriendViewModel
                            {
                                Id = member.UserId ?? string.Empty,
                                Name = member.UserName ?? string.Empty,
                                Avatar = member.Avatar
                            });
                        }
                    });
                }
            }
        }
        catch (Exception ex)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                MessageBox.Show($"加载群成员失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            });
        }
    }

    public async Task<bool> UpdateGroupNameAsync()
    {
        if (Name == _originalName) return true;

        var result = MessageBox.Show(
            $"确定要将群名称修改为\"{Name}\"吗？", 
            "修改群名称", 
            MessageBoxButton.OKCancel, 
            MessageBoxImage.Question);

        if (result == MessageBoxResult.OK)
        {
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Post, $"{NetWorkConfig.BaseUrl}/group/updatename");
                var content = new StringContent(
                    JsonSerializer.Serialize(new { 
                        userId = User.UserId,
                        groupId = GroupId,
                        newGroupName = Name
                    }), 
                    Encoding.UTF8, 
                    "application/json");
                request.Content = content;

                var response = await _httpClient.SendAsync(request);
                if (response.IsSuccessStatusCode)
                {
                    var jsonResponse = await response.Content.ReadAsStringAsync();
                    var updateResult = JsonDocument.Parse(jsonResponse).RootElement;
                    var code = updateResult.GetProperty("code").GetString();

                    if (code == "0000")
                    {
                        _originalName = Name;

                        GroupNameUpdated?.Invoke(GroupId, Name!);

                        await _groupRepository.UpdateGroupNameAsync(User.UserId, GroupId, Name!);
                        await _chatRecordRepository.UpdateGroupNameAsync(GroupId, Name!, User.UserId);


                        MessageBox.Show("群名称修改成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                        return true;
                    }
                    else
                    {
                        var message = updateResult.GetProperty("message").GetString();
                        MessageBox.Show($"群名称修改失败：{message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                
                MessageBox.Show("群名称修改失败，请稍后重试。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Name = _originalName;
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"修改群名称时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Name = _originalName;
                return false;
            }
        }
        else
        {
            Name = _originalName;
            return false;
        }
    }

    private async Task UpdateGroupAvatarAsync(string avatarPath)
    {
        try
        {
            using var formData = new MultipartFormDataContent();
            formData.Add(new StringContent(User.UserId), "UserId");
            formData.Add(new StringContent(GroupId), "GroupId");

            var avatarBytes = await File.ReadAllBytesAsync(avatarPath);
            var avatarContent = new ByteArrayContent(avatarBytes);
            avatarContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            formData.Add(avatarContent, "Avatar", Path.GetFileName(avatarPath));

            var response = await _httpClient.PostAsync($"{NetWorkConfig.BaseUrl}/group/updateavatar", formData);
            
            if (response.IsSuccessStatusCode)
            {
                var jsonResponse = await response.Content.ReadAsStringAsync();
                var updateResult = JsonDocument.Parse(jsonResponse).RootElement;
                var code = updateResult.GetProperty("code").GetString();
                var newAvatarPath= updateResult.GetProperty("newAvatar").GetString();

                if (code == "0000")
                {
                    Avatar = avatarPath;
                    _originalAvatar = Avatar;

                    GroupAvatarUpdated?.Invoke(GroupId, newAvatarPath!);


                    await _groupRepository.UpdateGroupAvatarAsync(User.UserId, GroupId, newAvatarPath!);
                    await _chatRecordRepository.UpdateGroupAvatarAsync(GroupId, newAvatarPath!, User.UserId);

                    MessageBox.Show("群头像修改成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    var message = updateResult.GetProperty("message").GetString();
                    MessageBox.Show($"群头像修改失败：{message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    Avatar = _originalAvatar;
                }
            }
            else
            {
                MessageBox.Show("群头像修改失败，请稍后重试。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Avatar = _originalAvatar;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"修改群头像时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            Avatar = _originalAvatar;
        }
    }
}
